/*
 * Project: book
 * 
 * File Created at 2017年9月12日
 * 
 * Copyright 2016 CMCC Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ZYHY Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license.
 */
package com.whb.book.common.encDec;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

/**
 * @Type HmacMd5.java
 * @Desc 
 * @author wanghb
 * @date 2017年9月12日 下午1:14:21
 * @version 
 */
public class HmacMd5 {

    private final static String ALGO = "HmacMD5";

    /**
     * 
     * getKey:(). <br/>
     * 
     * 
     * @author wanghb
     * @return
     * @since JDK 1.6
     */
    public static String getKey() {
        SecretKey key;
        try {
            KeyGenerator generator = KeyGenerator.getInstance(ALGO);
            key = generator.generateKey();
            return Base64.encodeBase64String(key.getEncoded());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 
     * enc:(). <br/>
     * 
     * 
     * @author wanghb
     * @param data
     * @param key
     * @return
     * @since JDK 1.6
     */
    public static byte[] enc(byte[] data, String key) {
        SecretKey secretKey;
        try {
            secretKey = new SecretKeySpec(Base64.decodeBase64(key), ALGO);
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            return mac.doFinal(data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 
     * enc:(). <br/>
     * 
     * 
     * @author wanghb
     * @param data
     * @param key
     * @return
     * @throws Exception
     * @since JDK 1.8
     */
    public static String enc(String data, String key) throws Exception {
        if (StringUtils.isEmpty(data) || StringUtils.isEmpty(data.trim())) {
            return null;
        }
        byte[] bytes = enc(data.getBytes("UTF-8"), key);
        return ByteUtil.bytes2hex(bytes);
    }

    public static void main(String[] args) throws Exception {
        String key = getKey();
        System.out.println(key);
        System.out.println(enc("123", key));
    }

}


/**
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2017年9月12日 wanghb create
 */